import Vue from 'vue'
import Vuex from 'vuex'
import { apiGet } from '@/utils/request'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 会话ID，直到关闭服务前都保存在内存中
    sessionId: null,
    // 语音状态：idle, recording, processing, playing
    voiceState: 'idle',
    // WebSocket连接状态
    websocketConnected: false,
    // 当前录音状态
    isRecording: false,
  },
  getters: {
    sessionId: (state) => state.sessionId,
    voiceState: (state) => state.voiceState,
    websocketConnected: (state) => state.websocketConnected,
    isRecording: (state) => state.isRecording,
  },
  mutations: {
    SET_SESSION_ID(state, id) {
      state.sessionId = id || null
    },
    SET_VOICE_STATE(state, status) {
      state.voiceState = status
    },
    SET_WEBSOCKET_CONNECTED(state, connected) {
      state.websocketConnected = connected
    },
    SET_RECORDING(state, recording) {
      state.isRecording = recording
    },
  },
  actions: {
    async fetchSessionId({ commit, state }) {
      // 如果已经存在 sessionId
      if (state.sessionId) {
        return;
      }

      try {
        const res = await apiGet('/api/user/sessionId')
        if (res && res.code === 200) {
          commit('SET_SESSION_ID', res.data)
        } else {
          // 401 或其他情况，置空
          commit('SET_SESSION_ID', null)
          // 如需提示，可使用 res.msg
        }
      } catch (err) {
        commit('SET_SESSION_ID', null)
      }
    },
    
    setVoiceState({ commit }, status) {
      commit('SET_VOICE_STATE', status)
    },
    
    setWebSocketConnected({ commit }, connected) {
      commit('SET_WEBSOCKET_CONNECTED', connected)
    },
    
    setRecording({ commit }, recording) {
      commit('SET_RECORDING', recording)
    },
  },
  modules: {},
})
